<template>
  <div id="chart-container" class="radar-echart" />
</template>

<script>
import * as echarts from 'echarts'
import { getDataAPI } from '@/api/echarts'

export default {
  //  组件中获取组件的dom元素
  mounted() {
    this.renderChart('bar')
  },
  methods: {
    async renderChart(type) {
      const { data } = await getDataAPI(type)
      let option = null

      if (type === 'bar') {
        option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['Done', 'Doing', 'Waiting']
          },
          xAxis: [
            {
              type: 'category',
              data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: 'Training Status',
              type: 'bar',
              data: data
            }
          ]
        }
      } else if (type === 'line') {
        option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['Series 1', 'Series 2']
          },
          xAxis: {
            type: 'category',
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: 'Series 1',
              type: 'line',
              data: data[0]
            },
            {
              name: 'Series 2',
              type: 'line',
              data: data[1]
            }
          ]
        }
      } else if (type === 'pie') {
        option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: '10%',
            top: '50%',
            data: data.map(item => item.name)
          },
          series: [
            {
              name: 'Pie Chart',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: 'center'
                }
              },
              data: data.map(item => ({
                value: item.value,
                name: item.name
              }))
            }
          ]
        }
      }
      const myChart = echarts.init(document.getElementById('chart-container'))
      myChart.setOption(option)
    }
  }
}
</script>

<style>
.radar-echart {
  width: 600px;
  height: 400px;
}
</style>
